package com.singzi.leetcode.N100;


import java.util.Arrays;

public class T0059 {
    public static void main(String[] args) {
        Solution0059 solution0059 = new Solution0059();
        System.out.println(Arrays.deepToString(solution0059.generateMatrix(10)));
    }
}
class Solution0059 {
    public int[][] generateMatrix(int n) {
        int [][]result = new int[n][n];
        int [][]visited = new int[n][n];

        int flag = 1,i = 0, j = 0, count = 1;
        addMatrix(result,visited,flag,i,j,count);

        return result;

    }
    public void addMatrix(int[][]matrix, int[][]visited, int flag, int i,int j, int count){
        if (count>matrix.length*matrix[0].length) return;
        switch (flag) {
            case 1: {
                if (j >= matrix[0].length || visited[i][j] == 1) {
                    j--;
                    flag = 2;
                    i++;
                    addMatrix(matrix, visited, flag, i, j, count);
                } else {
                    matrix[i][j] = count;
                    count++;
                    visited[i][j] = 1;
                    j++;
                    addMatrix(matrix, visited, flag, i, j, count);
                }
                break;

            }
            case 2 :{
                if (i >= matrix.length || visited[i][j] == 1) {
                    i--;
                    flag = 3;
                    j--;
                    addMatrix(matrix, visited, flag, i, j, count);
                } else {
                    matrix[i][j] = count;
                    count++;
                    visited[i][j] = 1;
                    i++;
                    addMatrix(matrix, visited, flag, i, j, count);
                }
                break;
            }
            case 3 :{
                if (j < 0 || visited[i][j] == 1) {
                    j++;
                    flag = 4;
                    i--;
                    addMatrix(matrix, visited, flag, i, j, count);
                } else {
                    matrix[i][j] = count;
                    count++;
                    visited[i][j] = 1;
                    j--;
                    addMatrix(matrix, visited, flag, i, j, count);
                }
                break;
            }
            case 4 :{
                if (i < 0 || visited[i][j] == 1) {
                    i++;
                    flag = 1;
                    j++;
                    addMatrix(matrix, visited, flag, i, j, count);
                } else {
                    matrix[i][j] = count;
                    count++;
                    visited[i][j] = 1;
                    i--;
                    addMatrix(matrix, visited, flag, i, j, count);
                }
                break;
            }
        }

    }
}
